package com.imut.hcdp.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.Producer;
import com.imut.hcdp.common.ImutContant;
import com.imut.hcdp.common.Rst;
import com.imut.hcdp.common.RedisCache;
import com.imut.hcdp.config.exception.ServiceException;
import com.imut.hcdp.domain.*;
import com.imut.hcdp.mapper.ConsumerMapper;
import com.imut.hcdp.service.IConsumerService;
import com.imut.hcdp.service.IHcdpRoleService;
import com.imut.hcdp.service.IHcdpUserService;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;


@RestController
@Slf4j
public class LoginController {

    /**
     * token失效时间
     */
    private static Integer EXPIRE_TIME = 1000;

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

        @Resource(name = "captchaProducerMath")
        private Producer captchaProducerMath;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IConsumerService iConsumerService;

    @Autowired
    private IHcdpUserService iHcdpUserService;

    @Autowired
    private IHcdpRoleService iHcdpRoleService;


    @GetMapping("/captchaImage")
    public Rst getCode(HttpServletResponse response) throws IOException
    {
        Rst ajax = Rst.success();
        // 保存验证码信息
        String verifyKey = ImutContant.CAPTCHA_CODE_KEY;
        String capStr = null, code = null;
        BufferedImage image = null;
        // 生成验证码
        String capText = captchaProducerMath.createText();
        capStr = capText.substring(0, capText.lastIndexOf("@"));
        code = capText.substring(capText.lastIndexOf("@") + 1);
        image = captchaProducerMath.createImage(capStr);
        //有效两分钟
        redisCache.setCacheObject(verifyKey, code, 30, TimeUnit.MINUTES);    // 转换流信息写出
        log.info("验证码：{}",code);
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return Rst.error(e.getMessage());
        }
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }

    @PostMapping("/consumerLogin")
    public Rst consumerLogin(@RequestBody LoginBody loginBody) {
        JSONObject user = new JSONObject();
        validateCaptcha(loginBody.getCode());
        String token = UUID.randomUUID().toString();
        if (loginBody.getUserType().equals(ImutContant.USER_TYPE_SYSTEM)) {
            HcdpUser hcdpUser = new HcdpUser();
            hcdpUser.setPhone(loginBody.getUsername());
            List<HcdpUser> hcdpUsers = iHcdpUserService.selectHcdpUserList(hcdpUser);
            if (CollectionUtils.isEmpty(hcdpUsers)) {
                throw new ServiceException("手机号未录入系统！");
            }
            HcdpUser temp = hcdpUsers.get(0);
            if (!loginBody.getPassword().equals(temp.getPwd())) {
                throw new ServiceException("密码有误！");
            }
            Long id = temp.getRoleid();
            HcdpRole hcdpRole = iHcdpRoleService.selectHcdpRoleById(id);
            JSONObject desc = new JSONObject();
            desc.put("role",hcdpRole);
            temp.setDesc(desc);
            redisTemplate.opsForValue().set(ImutContant.REDIS_USER_PREFIX + token, temp,EXPIRE_TIME, TimeUnit.MINUTES);
            user.put("userInfo",temp);
        }
        else if (loginBody.getUserType().equals(ImutContant.USER_TYPE_CONSUMER)) {
            Consumer consumer = new Consumer();
            consumer.setPhone(loginBody.getUsername());
            List<Consumer> consumers = iConsumerService.selectConsumerList(consumer);
            if (CollectionUtils.isEmpty(consumers)) {
                throw new ServiceException("手机号未录入系统！");
            }
            Consumer temp = consumers.get(0);
            if (!loginBody.getPassword().equals(temp.getPwd())) {
                throw new ServiceException("密码有误！");
            }
            JSONObject desc = new JSONObject();
            desc.put("role","顾客");
            temp.setDesc(desc);
            redisTemplate.opsForValue().set(ImutContant.REDIS_USER_PREFIX + token, temp,30, TimeUnit.MINUTES);
            user.put("userInfo",temp);
        } else {
            throw new ServiceException("用户类型异常");
        }
        user.put("token",token);
        return Rst.success("登陆成功", user);
    }

    /**
     * 注册
     * @param consumer
     * @return
     */
    @PostMapping("/register")
    public Rst register(@RequestBody Consumer consumer){

        List<Consumer> consumers = iConsumerService.selectConsumerList(new Consumer().setUsername(consumer.getUsername()));
        if(!CollectionUtils.isEmpty(consumers)){
            throw new ServiceException("用户名已存在！");
        }
        List<Consumer> consumers1 = iConsumerService.selectConsumerList(new Consumer().setCard(consumer.getCard()));
        if(!CollectionUtils.isEmpty(consumers1)){
            throw new ServiceException("身份证号已存在！");
        }
        List<Consumer> consumers2 = iConsumerService.selectConsumerList(new Consumer().setPhone(consumer.getPhone()));
        if(!CollectionUtils.isEmpty(consumers2)){
            throw new ServiceException("手机号已注册！");
        }
        consumer.setCrttime(new Date());
        consumer.setPwd("123456");
        iConsumerService.insertConsumer(consumer);
        return Rst.success("用户注册成功!默认密码为：123456");
    }


    /**
     * 验证码
     * @param code
     */
    private void validateCaptcha(String code) {
        String verifyKey = ImutContant.CAPTCHA_CODE_KEY ;
        String captcha = redisCache.getCacheObject(verifyKey);
//        redisCache.deleteObject(verifyKey);  todo测试完毕要关了
        if (captcha == null) {
            throw new ServiceException("验证码过期，请重新生成！");
        }
        if (!code.equalsIgnoreCase(captcha)) {
            throw new ServiceException("验证码错误！");
        }
    }
}
